package com.fenghen.service.impl;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.fenghen.config.CodeGenerator;
import com.fenghen.entity.CodeGeneratorConfig;
import com.fenghen.service.CodeGeneratorService;
import org.springframework.stereotype.Service;

import java.sql.Types;
import java.util.Collections;

@Service
public class CodeGeneratorServiceImpl implements CodeGeneratorService {

    /**
     * 示例请求体
     * {
     *     "jdbcUrl": "jdbc:mysql://127.0.0.1:3306/ceshi?useSSL=false&serverTimezone=UTC",
     *     "username": "root",
     *     "password": "123456a",
     *     "author": "wangba",
     *     "outputDir": "H://generator",
     *     "parentPackage": "com.fenghen",
     *     "moduleName": "genertaor",
     *     "xmlPath": "H://generator//xml",
     *     "tableNames": ["demo01", "dept", "emp"],
     *     "tablePrefixes": ["t_", "c_"]
     * }
     * @param config
     */

    @Override
    public void generateCode(CodeGeneratorConfig config) {
        FastAutoGenerator.create(config.getJdbcUrl(), config.getUsername(), config.getPassword())
                .globalConfig(builder -> {
                    builder.author(config.getAuthor()) // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .outputDir(config.getOutputDir()); // 指定输出目录
                })
                .dataSourceConfig(builder ->
                        builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                            int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                            if (typeCode == Types.SMALLINT) {
                                // 自定义类型转换
                                return DbColumnType.INTEGER;
                            }
                            return typeRegistry.getColumnType(metaInfo);
                        })
                )
                .packageConfig(builder ->
                        builder.parent(config.getParentPackage()) // 设置父包名
                                .moduleName(config.getModuleName()) // 设置父包模块名
                                .pathInfo(Collections.singletonMap(OutputFile.xml, config.getXmlPath())) // 设置mapperXml生成路径
                )
                .strategyConfig(builder -> {
                    builder.addInclude(config.getTableNames().toArray(new String[0])); // 设置需要生成的表名
                    if (config.getTablePrefixes() != null && !config.getTablePrefixes().isEmpty()) {
                        builder.addTablePrefix(config.getTablePrefixes().toArray(new String[0])); // 设置过滤表前缀
                    }
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                .execute();
    }
}
